package com.github.niefy.common.handler;

import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.niefy.modules.wx.entity.WxAccount;
import com.github.niefy.modules.wx.entity.WxUser;
import com.github.niefy.modules.wx.service.WxAccountService;
import com.github.niefy.modules.wx.service.WxUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author yucl
 * @create 2021/6/28 16:05
 */
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "iview-admin-wechat",
        topic = "iview-admin-wechat"
)
@Service
public class RockerMQListenerHandler implements RocketMQListener<WxMpXmlMessage> {


    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private  WxMpService wxMpService;

    @Autowired
    private WxAccountService wxAccountService;

    @Override
    public void onMessage(WxMpXmlMessage wxMpXmlMessage) {

        log.info("收到一个消息:{}", wxMpXmlMessage);
        try {
            String content = wxMpXmlMessage.getContent();
            String  phone= content.split(":")[1].trim();
            String nickname = "nickname";
            String openId = wxMpXmlMessage.getFromUser();
            WxUser wxUser = wxUserService.getById(openId);
            if(wxUser == null){
                wxUser = new WxUser();
                wxUser.setAppid("0");
            }
            wxUser.setPhone(phone);
            wxUser.setNickname(nickname);
            wxUser.setOpenid(openId);
            wxUserService.saveOrUpdate(wxUser);

            //刷新粉丝列表
            ThreadUtil.execAsync(() -> {

                List<WxAccount> wxAccountList =  wxAccountService.list();
                wxAccountList.stream().forEach(wxAccount -> {
                    wxMpService.switchoverTo(wxAccount.getAppid());

                    List<String> openids = new ArrayList<>();
                    openids.add(openId);
                    wxUserService.syncWxUsers(openids,wxAccount.getAppid());
                });
            });


        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
